<template>
  <div>
    <!-- 搜索添加栏 -->
    <Row>
      <Card>
        <Form ref="searchData" :model="searchData" :label-width="80">
          <Row>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="指标名称" prop="indexName">
                <Input
                  v-model="searchData.indexName"
                  suffix="ios-search"
                  placeholder="请输入指标名称"
                  style="width: auto"
                >
                  <Icon type="ios-search" slot="suffix" />
                </Input>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="选择年份" prop="dateTime">
                <DatePicker
                  type="year"
                  format="yyyy"
                  v-model="searchData.dateTime"
                  @on-change="handlerFormat"
                  placeholder="请选择指标年份"
                  style="width: auto"
                ></DatePicker>
              </FormItem>
            </i-col>
            <i-col :xs="24" :md="12" :lg="6">
              <FormItem label="考核单位" prop="leadUnit">
                <Select filterable clearable placeholder="请选择考核单位" v-model="searchData.leadUnit">
                  <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </FormItem>
            </i-col>
          </Row>

          <FormItem>
            <Button

              type="primary"
              style="marigin:0 20px"
              :loading="searchLoading"
              @click="searchSubmit(10,1)"
            >提交搜索</Button>
            <Button @click="submitReset('searchData')">重置搜索</Button>
          </FormItem>
        </Form>
      </Card>
    </Row>
    <Row style="margin-top:20px">
      <Card>
        <div class="btn-arrs">
            <Button type="info"  @click="showUserModal"  v-if="isSpuerAdmins.add">添加县直单位指标</Button>
        </div>
        <Table   :loading="tabelLoading" :columns="tableHead" :data="tableData" border></Table>
        <div style="margin-top:20px;margin-left:35%">
          <Page
            @on-change="pageNumberChange"
            :page-size="pageSize"
            :total="pageTotal"
            @on-page-size-change="pageSizeChange"
            show-elevator
            show-sizer
          />
        </div>
      </Card>
    </Row>
    <!-- 添加 -->
    <Modal
      v-model="isrModal"
      :title="ModalTitles"
      :loading="ModalLoading"
      @on-cancel="cancelUserModal"
    >
      <Form ref="indexMagement" :model="modalForms" :rules="formReg" :label-width="80">
        <Row>
          <Col span="24">
            <FormItem label="指标名称" prop="indexName">
              <Input v-model="modalForms.indexName" placeholder="请输入指标名称"></Input>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem label="考核单位" prop="leadUnit">
              <Select filterable clearable v-model="modalForms.leadUnit" placeholder="请选择考核单位">
                <Option
                    v-for="item in getDepartmentList"
                    :value="item.departcode"
                    :key="item.departcode"
                  >{{ item.department }}</Option>
                </Select>
              </Select>
            </FormItem>
          </Col>
          <Col span="11">
            <FormItem label="指标年份" prop="dateTime">
              <DatePicker
                type="year"
                format="yyyy"
                :value="modalForms.dateTime"
                @on-change="IndexFormat"
                placeholder="请选择指标年份"
                style="width:185px"
              ></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
      <div slot="footer">
        <Button  v-if="isSpuerAdmins.add"  type="primary" size="large" :loading="ModalLoading" @click="submitUserModal">提交</Button>
        <Button size="large" @click="cancelUserModal">取消</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { hasOneOf } from "@/libs/tools";
import { countryUnitMangeAjax } from "@/api/countyUnit";
// 删除URL
const DELETE_URL = "/countryUnitIndicators/delete";
// 修改URL
const UPDATE_URL = "/countryUnitIndicators/update";
// 添加URL
const INSERT_URL = "/countryUnitIndicators/insert";
// 查询URL
const QUERY_URL = "/countryUnitIndicators/query";

const INSERT_TITLE = "添加";
const UPDATE_TITLE = "编辑";
export default {
  data() {
    // 验证手机号码
    return {
      // 是否为超级管理员
      isSpuerAdmins: {
        add: true,
        action: "inline-block"
      },
      isrModal: false, // 模态框
      searchLoading: false, // 搜索Loading
      ModalLoading: false, // 提交loading
      tabelLoading: false, // 表格loading
      ModalTitles: "", // 模态框title
      isResponsible: "",
      pageSize: 10,
      pageNumber: 1,
      pageTotal: 10,
      modalForms: {
        indexName: "", // 指标名称
        leadUnit: "", // 考核单位
        dateTime: "" // 年份
      },
      searchData: {
        leadUnit: "", // 考核单位
        indexName: "", // 指标名称
        dateTime: "" // 年份
      },
      tableData: [], // 表格数据

      formReg: {
        classname: [
          {
            required: true,
            message: "请输入分类名",
            trigger: "blur"
          }
        ]
      },
      tableHead: [
        {
          title: "序号",
          type: "index",
          width: 80,
          align: "center"
        },
        {
          title: "指标名称",
          key: "indexName"
        },
        {
          title: "考核单位",
          key: "leadUnitName"
        },
        {
          title: "年份",
          key: "dateTime",
          width: 150
        },

        {
          title: "操作",
          key: "action",
          width: 220,
          align: "center",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary"
                  },
                  style: {
                    marginRight: "5px"
                  },
                  on: {
                    click: () => {
                      this.modalForms = JSON.parse(JSON.stringify(params.row));
                      this.ModalTitles = "编辑";
                      this.isrModal = true;
                      // 如果编辑时候可以显示出来， 但是不可填写
                      if (!this.accessAdmin) {
                        this.roleSelect = true;
                      }
                      this.isResponsible = true;
                    }
                  }
                },
                "查看或编辑"
              ),
              h(
                "Button",
                {
                  props: {
                    type: "error"
                  },
                  style: {
                    display: this.isSpuerAdmins.action
                  },
                  on: {
                    click: () => {
                      this.deleteIndex(params.row);
                    }
                  }
                },
                "删除"
              )
            ]);
          }
        }
      ]
    };
  },
  methods: {
    // 搜索
    searchSubmit(pageSize, pageNumber) {
      this.searchLoading = true;
      this._getData(this.searchData, QUERY_URL, pageSize, pageNumber);
    },
    // 重置搜索
    submitReset(name) {
      this.searchLoading = false;
      this.$refs[name].resetFields();
    },
    // 搜索框年份
    handlerFormat(year) {
      this.searchData.dateTime = year;
    },
    // FORM表单年份
    IndexFormat(year) {
      this.modalForms.dateTime = year;
    },
    // 删除指标
    deleteIndex(row) {
      if (this.accessAgent) {
        this.$Message.error("权限不足！");
        return;
      }
      this.$Modal.confirm({
        title: "删除此条信息",
        content: "<p>删除完成后将无法恢复</p>",
        loading: true,
        onOk: () => {
          this._addOrUpdate(row, DELETE_URL).then(result => {
            this.$Modal.remove();
            if (result.code === "200") {
              this.$Message.info("删除成功!");
              this._getData(
                this.tableData,
                QUERY_URL,
                this.pageSize,
                this.pageNumber
              );
            } else {
              this.$Message.error("删除失败！");
            }
          });
        }
      });
    },
    // 显示模态框
    showUserModal() {
      this.ModalTitles = "添加";
      this.isrModal = true;
      this.roleSelect = false;
      // 登录角色不是admin,只能添加自己部门的啊
      if (!this.accessAdmin) {
        this.modalForms.userDepartment = this.getDepartment;
      }
      // 添加，责任人只能添加经办人
      if (this.accessAdmin) {
        3;
        this.isResponsible = true;
      } else {
        this.isResponsible = false;
      }
    },
    // 提交
    submitUserModal() {
      this.$refs["indexMagement"].validate(valid => {
        if (valid) {
          this.ModalLoading = true;
          if (this.ModalTitles === INSERT_TITLE) {
            this._addOrUpdate(this.modalForms, INSERT_URL).then(result => {
              this.isrModal = false;
              this.ModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error(result.message);
              }
            });
          } else if (this.ModalTitles === UPDATE_TITLE) {
            this._addOrUpdate(this.modalForms, UPDATE_URL).then(result => {
              this.isrModal = false;
              this.ModalLoading = false;
              if (result.code === "200") {
                this.$Message.success("添加成功！");
                this._getData(
                  this.searchData,
                  QUERY_URL,
                  this.pageSize,
                  this.pageNumber
                );
              } else {
                this.$Message.error("添加失败！");
              }
            });
          }
        } else {
          this.$Message.error("请填写完整！");
        }
      });
    },
    cancelUserModal() {
      this.$refs["indexMagement"].resetFields();
      this.ModalLoading = false;
      this.isrModal = false;
      this.modalForms = {
        department: "" // 用户部门
      };
    },
    // 页码
    pageNumberChange(pageNumber) {
      this.pageNumber = pageNumber;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 页数
    pageSizeChange(pageSize) {
      this.pageSize = pageSize;
      this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    },
    // 添加/修改
    _addOrUpdate(formData, url) {
      const keyOne = "countryUnitIndicatorsEntity";
      return new Promise((resolve, reject) => {
        countryUnitMangeAjax({ formData, url, keyOne })
          .then(result => {
            if (result.data !== undefined) {
              resolve(result.data);
            } else {
              reject(err);
            }
          })
          .catch(err => {
            console.log(err);
          });
      });
    },
    // 查询
    _getData(formData, url, pageSize, pageNumber) {
      this.tabelLoading = true;
      formData = Object.assign(formData, {
        pageSize,
        pageNumber
      });
      const keyOne = "countryUnitIndicatorsFilter";
      countryUnitMangeAjax({ formData, url, keyOne })
        .then(result => {
          this.tabelLoading = false;
          if (result.data.code === "200") {
            this.searchLoading = false;
            this.tableData = result.data.results.list;
            // this.pageTotal = result.data.results.pageTotal;
            this.$Message.success("查询成功");
          } else {
            this.$Message.error("查询失败");
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  mounted() {},
  created() {
    this._getData(this.searchData, QUERY_URL, this.pageSize, this.pageNumber);
    // 获取是否为超级管理员
    let isSuperAdmin = sessionStorage.getItem("isSuperAdmin");
    this.globalFunction2(isSuperAdmin);
  },
  computed: {
    getDepartmentList() {
      return this.$store.state.user.departmentList;
    },
    getDepartment() {
      return this.$store.state.user.department;
    },
    access() {
      return this.$store.state.user.access;
    },
    // 管理员
    accessAdmin() {
      return hasOneOf(["admin"], this.access);
    },
    // 责任人
    accessRespons() {
      return hasOneOf(["responsible"], this.access);
    },
    // 经办人
    accessAgent() {
      return hasOneOf(["agent"], this.access);
    }
    //
  }
};
</script>
<style scoped>
</style>
